package cn.xenoscode.simplepool.controller;

import cn.xenoscode.simplepool.mqtt.SimpleMqttClient;
import cn.xenoscode.simplepool.mqtt.SimpleMqttPool;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Xenos
 * @version V1.0
 * @Package xenoscode.cn.mqttpool.controller
 * @date 2020/9/4 22:59
 */
@RestController
public class TestController {
    @Autowired
    private SimpleMqttPool mqttPool;

    /**
     * 每次调用该接口，向服务器推送100条数据
     */
    @GetMapping("/test/publish")
    public void publishTest() {
        byte[] payload = "publish test".getBytes();
        MqttMessage mqttMessage = new MqttMessage();
        mqttMessage.setQos(2);
        mqttMessage.setPayload(payload);
        String topic = "PUBLISH_TEST";
        int times = 100;
        for (int i = 0; i < times; i++) {
            try {
                SimpleMqttClient client = mqttPool.getClient();
                client.publish(topic, mqttMessage);
                mqttPool.releaseClient(client);
            } catch (Exception e) {
                System.out.println(e.toString());
            }
        }
    }

    /**
     * 每次调用该接口，开辟多个线程进行向服务器推送数据，每次线程推送100条
     */
    @GetMapping("/test/publish/mutil")
    public void mutilPublishTest() {
        byte[] payload = "publish test".getBytes();
        MqttMessage mqttMessage = new MqttMessage();
        mqttMessage.setQos(2);
        mqttMessage.setPayload(payload);
        String topic = "PUBLISH_TEST";

        int threadCount = 5;
        for (int i = 0; i < threadCount; i++) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    int times = 100;
                    for (int j = 0; j < times; j++) {
                        try {
                            SimpleMqttClient client = mqttPool.getClient();
                            client.publish(topic, mqttMessage);
                            mqttPool.releaseClient(client);
                        } catch (Exception e) {
                            LoggerFactory.getLogger(TestController.class).error(e.toString());
                        }
                    }
                }
            });
            thread.start();
        }
    }
}
